#include "common.h"
#include "shell.h"
#include "app_task.h"
#include "app_reserve_day.h"
static uint32_t day_tick;
static uint32_t real_time_remain;      //记录授权剩余天数

uint32_t get_reserved_days(void)
{
    return real_time_remain;
}

void set_reserved_days(uint32_t time)
{
    real_time_remain = time;
}


void day_tick_clear(void)
{
    day_tick = 0;
}

static void get_reserved_days_cmd(int argc, char *argv[])
{
    elog_info("reserved days:%d", get_reserved_days());
}
SHELL_EXPORT_CMD(SHELL_CMD_PERMISSION(0)|SHELL_CMD_TYPE(SHELL_TYPE_CMD_MAIN)|SHELL_CMD_DISABLE_RETURN, get_reserved_days, get_reserved_days_cmd, get reserved days);


static void set_reserved_days_cmd(int argc, char *argv[])
{
    int day;
    int lens;
    //1.检测输入参数个数
    if(2 != argc)
    {
        goto err;
    }

    //2.获取输入参数内容
    lens = strlen(argv[1]);
    for(int i = 0; i < lens; i++)
    {
        if((argv[1][i] < '0') || (argv[1][i] > '9'))
        {
            goto err;
        }
    }

    day = atoi(argv[1]);
    if((day < 0) || (day > 65534))
    {
        goto err;
    }

    //3.存储授权时间
    day_tick_clear();
    set_reserved_days(day);


    //4.存储授权时间到flash
    flash_operation_t operation;
    operation.type = FLASH_TIME_REMAIN;
    operation.time_remain = day;
    flash_operation_notify(operation);

    elog_info("set reserved days:%d", get_reserved_days());
    return;
err:
    elog_error("Invalid input paramter, please input between 0 and 65534.");
}
SHELL_EXPORT_CMD(SHELL_CMD_PERMISSION(0)|SHELL_CMD_TYPE(SHELL_TYPE_CMD_MAIN)|SHELL_CMD_DISABLE_RETURN, set_reserved_days, set_reserved_days_cmd, please input between 0 and 65534.);

void reserved_days_handler(void)
{
    if((TIME_REMAIN_FOREVERY <= get_reserved_days()) || (TIME_REMAIN_STOP == get_reserved_days()))
    {
        //do nothing
    }
    else
    {
        day_tick++;
        //运行时间+1天
        if(day_tick > TIME_REMAIN_UPDATE_TIME)
        {
            day_tick = 0;
            int day = get_reserved_days();
            day -= 1;
            if(day < 0) day = 0;
            set_reserved_days(day);
            flash_operation_t operation;
            operation.type = FLASH_TIME_REMAIN;
            operation.time_remain = day;
            flash_operation_notify_from_ISR(operation);
        }
    }
}
